# -*- coding: utf-8 -*-
import os
from datetime import datetime
import re


from DrissionPage import Chromium
from PyQt5.QtCore import QThread, pyqtSignal

from app import helper
from app.tab_pool import TabPool


class DealDataPlan(QThread):
    progress_signal = pyqtSignal(int)  # 进度信号（0-100）

    def __init__(self):
        super().__init__()

        self.page_count = None
        self.total = None
        self.data = []
        self.browser = Chromium()
        self.page_index = 1
        self.deal_num = 0
        # self.pool = TabPool(size=8)

    def init(self):
        self.page_count = None
        self.total = None
        self.data = []
        self.page_index = 1
        self.deal_num = 0

    def open_login(self):
        self.browser.latest_tab.get('https://xcsh.cnca.cn/checker/a/login')

    def do(self):
        page = self.browser.latest_tab
        # page.get('https://xcsh.cnca.cn/checker/a/manage/tbClockIn/list')
        # page.ele('x://*[@id="searchForm"]/table/tbody/tr[8]/td/input[1]').click()

        page_html_list = page.eles('x:/html/body/div[1]/ul/li')
        page_html = page_html_list[-1]
        page_list = page_html.eles('t:input')
        page_size = page_list[-1].value
        page_str = page_html.text
        temp = re.findall(r'\d+', page_str)
        self.total = int(temp[-1])
        self.page_count = self.total // int(page_size) + 1
        self.get_page_data(page)
        for i in range(0, self.page_count - 1):
            page.actions.click('@@tag()=a@@text()=下一页 »')
            # page.ele('@@tag()=a@@text()=下一页 »').click()
            page.wait.load_start()  # 等待新页面开始加载
            page.wait.doc_loaded()
            self.get_page_data(page)

        # print(self.data)
        # return False
        # 单线程
        # for item in self.data[1:]:
        #     self.do_detail(item)

        # 多线程
        pool = TabPool(size=8)
        for item in self.data[1:]:
            pool.operate(self.get_detail_tab, row=item, link=item[-1])
        pool.close_web_page_pool()
        current_time = datetime.now().strftime('%Y%m%d%H%M%S')
        path = './excel'
        if not os.path.exists(path):
            os.mkdir(path)
        filename = f'{path}/output_{current_time}.xlsx'
        helper.save_excel(self.data, filename)
        self.progress_signal.emit(100)
        print('处理完成，共%d条数据' % self.total)

    def do_detail(self, row):
        item = {
            'row': row,
            'link': row[-1],
        }
        self.get_detail_tab(self.browser.latest_tab, item)

    def get_page_data(self, page):
        print('共%d页，正在获取第%d页' % (self.page_count, self.page_index))
        self.page_index += 1
        if len(self.data) == 0:
            titles = page.eles('x://*[@id="contentTable"]/thead/tr/th').get.texts()
            titles.append('审核组')
            titles.append('首次会签到')
            titles.append('首次会签到地点偏差')
            titles.append('首次会议照片时间')
            titles.append('认证到审核组首次签到照片时间')
            titles.append('末次会签退')
            titles.append('末次会签退地点偏差')
            titles.append('末次会议照片时间')
            titles.append('认证到审核组末次签到照片时间')
            titles.append('技术专家')
            titles.append('多场所地址')
            titles.append('备注')
            self.data.append(titles)
        trs = page.eles('x://*[@id="contentTable"]/tbody/tr')
        for tr in trs:
            tds = tr.eles('x://td')
            temp = tds.get.texts()
            link = tr.ele('x:/td[4]/a').attr('href')
            temp.append(link)
            # self.get_detail(temp, link)

            self.data.append(temp)

    def aaa(self, tab, kwargs):
        print(kwargs)
        tab.get("https://www.baidu.com")
        tab.ele('#kw').input('hello world')
        tab.ele('#su').click()

    def get_detail_tab(self, tab, kwargs):
        try:
            row = kwargs['row']
            link = kwargs['link']
            tab.get(link)
            tab.wait.ele_displayed('x://*[@id="contentTable"]/tbody/tr[3]/td[2]/div[1]', 20)
            tab.stop_loading()
            # 审核计划信息
            table_1 = tab.ele('x:/html/body/table[1]')
            # 审核地址
            row[5] = tab.ele('x://*[@id="tbOdsCheckplanTable"]/tr/td[6]').text

            # 审核组
            row.append(table_1.ele('x://tr/td[12]').text)
            # 签到信息
            table_2 = tab.ele('x:/html/body/form/table')
            # 照片
            table_3 = tab.ele('x:/html/body/table[2]')
            # 签到
            begin_data = []
            end_data = []
            for item in table_2.eles('t:tr'):
                temp = item.eles('t:td').get.texts()
                if not temp:
                    continue
                if temp[5] == '首次会签到':
                    begin_data = temp
                elif  temp[5] == '末次会签退':
                    end_data = temp
            if begin_data:
                # 首次会签到
                row.append(begin_data[4])
                # 首次会签到地点偏差
                row.append(begin_data[6].replace(' ', ''))
                # 首次会议照片时间
                s_date_list = table_3.eles('x://tr[1]/td[2]/div').get.texts()
                if len(s_date_list) > 0:
                    row.append(self.deal_date(s_date_list[0]))
            else:
                row.append('')
                row.append('')
                row.append('')

            # 其他照片
            date_ele = table_3.eles('x://tr[3]/td[2]/div')
            if date_ele:
                date_list = date_ele.get.texts()
                self.fill_list(date_list, 2)

            else:
                date_list = ['','']
            # 认证到审核组首次签到照片时间
            row.append(self.deal_date(date_list[0]))

            if end_data:
                # 末次会签到
                row.append(end_data[4])
                # 末次会签到地点偏差
                row.append(end_data[6].replace(' ', ''))
                # 末次会议照片时间
                e_date_list = table_3.eles('x://tr[2]/td[2]/div').get.texts()
                if len(e_date_list) > 0:
                    row.append(self.deal_date(e_date_list[0]))
            # 认证到审核组末次签到照片时间
            row.append(self.deal_date(date_list[1]))
            tab.ele('x://*[@id="tbOdsCheckplanTable"]/tr/td[16]/a').click(by_js=True)
            zhuanjia = tab.ele('x://*[@id="inputForm"]/table/tbody/tr[8]/td[4]').text
            row.append(zhuanjia)
            note = tab.ele('x://*[@id="inputForm"]/table/tbody/tr[12]/td[2]').text
            if '多现场' not in note:
                row.append('')
            row.append(note)
            self.deal_num += 1
            self.update_progress()
        except  Exception as e:
            print(e)

    def get_detail(self, row, link):
        d_page = self.browser.new_tab(link)
        d_page.wait.ele_displayed('x://*[@id="contentTable"]/tbody/tr[3]/td[2]/div[1]', 20)
        d_page.stop_loading()
        s_date_list = d_page.eles('x://*[@id="contentTable"]/tbody/tr[1]/td[2]/div').get.texts()
        if len(s_date_list) > 0:
            row.append(self.deal_date(s_date_list[0]))
        e_date_list = d_page.eles('x://*[@id="contentTable"]/tbody/tr[2]/td[2]/div').get.texts()
        if len(e_date_list) > 0:
            row.append(self.deal_date(e_date_list[0]))
        d_page.ele('x://*[@id="tbOdsCheckplanTable"]/tr/td[16]/a').click(by_js=True)
        note = d_page.ele('x://*[@id="inputForm"]/table/tbody/tr[12]/td[2]').text
        row.append(note)
        d_page.close()

    def update_progress(self):
        progress = self.deal_num / self.total * 100
        self.progress_signal.emit(int(progress))

    def deal_date(self, text):

        # 定义匹配日期时间的正则表达式
        pattern = r'(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})'
        match = re.search(pattern, text)
        if match:
            return match.group(1)
        else:
            return ''

    def fill_list(self, lst, length):
        _len = len(lst)
        if _len >= length:
            return
        for i in range(length - _len):
            lst.append('')

    def run(self):
        self.do()


if __name__ == '__main__':
    row = ['https://xcsh.cnca.cn/checker/a/task/tbOdsCheckplan/tbCList?planNo=a1773f2b96ab5656904c5dd26f28bcde&planId=8a6ad75781686c9eb2d60ad66150dfa5&pageSize=10']
    DealData().do_detail(row)
    print(row)